package com.lagou.dao.impl;

import com.lagou.dao.StudentService;
import com.lagou.entity.Student;
import com.lagou.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class StudentServiceImpl implements StudentService {


    @Override
    public List<Student> getStudentList() {

        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        String sql = "SELECT stuno AS \"stuNo\" ,stuname AS \"stuName\" ,sex, birthday  FROM student  ";

        try {
            List<Student> stuList = qr.query(sql,new BeanListHandler<Student>(Student.class));

            return stuList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addStudent(Map map) {

        String stuNo = (String) map.get("stuNo");
        String stuName = (String) map.get("stuName");
        String sex = (String) map.get("sex");
        String birthday = (String) map.get("birthday");

        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        String sql = "INSERT INTO `student` (`stuno`, `stuname`, `sex`, `birthday`) VALUES (?, ?, ?, ?); ";

        Object[] params = {stuNo,stuName,sex,birthday};
        //执行queryrunner的插入方法

        int row = 0;
        try {
            row = qr.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }

        return row;
    }
}
